package com.zsk.shop.config.interceptor;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.base.BizException;
import com.zsk.shop.common.base.NoMsgException;
import com.zsk.shop.common.utils.DingTalkRootUtil;
import com.zsk.shop.service.GlobalExceptionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.ConstraintViolationException;
import java.io.PrintWriter;
import java.io.StringWriter;

@ResponseBody
@ControllerAdvice
public class ErrorHandler {
    private final static Logger logger = LoggerFactory.getLogger(ErrorHandler.class);

    @Autowired
    private DingTalkRootUtil dingTalkRootUtil;
    @Resource
    private GlobalExceptionService globalExceptionService;

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error("验证参数返回,{}", e.getBindingResult().getFieldError().getDefaultMessage());
        return BaseResponse.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public BaseResponse constraintViolationException(ConstraintViolationException e) {
        logger.error("验证参数返回,{}", e.getMessage());
        return BaseResponse.error("您发布的内容包含了敏感词");
    }

    @ExceptionHandler(BizException.class)
    public BaseResponse handlerBusinessException(BizException e) {
        logger.error("BizException业务异常,{},{}", e.getCode(), e.getErrorMessage());
        sendExceptionDing(e);
        return new BaseResponse(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(NoMsgException.class)
    public BaseResponse handlerBusinessException(NoMsgException e) {
        logger.error("NoMsgException业务异常,{},{}", e.getCode(), e.getErrorMessage());
        return new BaseResponse(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(JsonMappingException.class)
    public BaseResponse handlerException(JsonMappingException e) {
        logger.error("json格式错误", e);
        sendExceptionDing(e);
        return new BaseResponse(999, e.getMessage());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public BaseResponse handlerException(HttpMessageNotReadableException e) {
        logger.error("错误", e);
        sendExceptionDing(e);
        return new BaseResponse(999, e.getMessage());
    }

    @ExceptionHandler(JsonParseException.class)
    public BaseResponse handlerException(JsonParseException e) {
        logger.error("json格式错误", e);
        sendExceptionDing(e);
        return new BaseResponse(999, e.getMessage());
    }

    @ExceptionHandler(InvalidFormatException.class)
    public BaseResponse handlerException(InvalidFormatException e) {
        logger.error("错误", e);
        sendExceptionDing(e);
        return new BaseResponse(999, e.getMessage());
    }

    @ExceptionHandler(Throwable.class)
    public BaseResponse handlerException(Exception e) {
        logger.error("SYS_ERROR", e);
        if (!e.getMessage().contains("Request method 'GET' not supported")) {
            sendExceptionDing(e);
        } else {
            globalExceptionService.add(e, e.getClass());
        }
        return new BaseResponse(999, e.getMessage());
    }

    /**
     * 发送 钉钉异常提醒
     *
     * @param e
     */
    private void sendExceptionDing(Exception e) {
        globalExceptionService.add(e, e.getClass());
        //请求参数
        String content = "\n" + e.getMessage() + "\n" + getExceptionText(e);
        dingTalkRootUtil.send(content, "", false);
    }

    /**
     * e.printStackTrace() to String
     *
     * @param e
     * @return
     */
    public static String getExceptionText(Exception e) {
        String text = "";
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        text = sw.toString();
        text = text.replaceAll("\r", "");
        text = text.replaceAll("\n", "|");
        text = text.replaceAll("\t", "");
        return text;
    }

}
